package xx.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    /**
     * 需要拥有ROLE_SUPERADMIN角色才可访问
     * @return
     */
    @RequiresRoles("ROLE_SUPERADMIN")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

    /**
     * 测试 无需权限和角色认证
     * @return
     */
    @GetMapping("/test")
    public String test() {
        return "norole success!";
    }

    /**
     * 需要拥有USER_UPDATE权限才可访问
     * @return
     */
    @RequiresPermissions("USER_UPDATE")
    @GetMapping("/update")
    public String update() {
        return "update success!";
    }

    /**
     * 需要拥有USER_ADD权限才可访问
     * @return
     */
    @RequiresPermissions("USER_ADD")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }


    /**
     * 方法权限认证
     *
     * @return
     */
    @RequestMapping("save")
    public String save() {
        //基于角色
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        //代码方式
        if (subject.hasRole("admin")) {
            System.out.println("保存订单!");
        } else {
            System.out.println("无权访问!");
        }
        System.out.println("进入save方法============");
        return "redircet:/index.jsp";
    }

    @RequiresRoles(value = {"admin", "user"})//用来判断角色  同时具有 admin user
    @RequiresPermissions("user:update:01") //用来判断权限字符串
    public String save2() {
        System.out.println("进入方法");
        return "redirect:/index.jsp";
    }
}
